package se.lnu.axez;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import android.content.Context;

/**
 * Manages all triangular meshes. Provides means for loading, caching and
 * reusing the models.
 * 
 * @author stan
 * 
 */
public final class TriMeshManager {
	private final static String TAG = TriMeshManager.class.getName();

	private final Context androidContext;
	
	/**
	 * Holds references on all registered tri-meshes keyed by their types.
	 */
	private final Map<Class<? extends TriMesh>, TriMesh> meshes = new HashMap<Class<? extends TriMesh>, TriMesh>();

	public TriMeshManager(Context androidContext) {

		this.androidContext = androidContext;
	}

	/**
	 * Creates new trimesh instance of specified type or returns existing
	 * instance if it is already registered in the manager.
	 * 
	 * @param type
	 *            - {@link TriMesh} successor type.
	 */
//	public <E extends TriMesh> E getTriMesh(Class<E> type) {
//		return Utils.getOrCreate(type, this.meshes);
//	}

	public TriMesh getTriMesh(int triMeshResourceId) {
		final InputStream is = androidContext.getResources().openRawResource(triMeshResourceId);
		try {
			ObjectInputStream ois = new ObjectInputStream(new GZIPInputStream(new BufferedInputStream(is)));
			return (TriMesh) ois.readObject();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	TriMeshManager disposeAll() {
		this.meshes.clear();
		return this;
	}
}
